package com.developer.platform.domain.service.impl;

import com.developer.platform.domain.Menu;
import com.developer.platform.domain.event.MenuEvent;
import com.developer.platform.domain.event.MenuEventPublisher;
import com.developer.platform.domain.service.IMenuService;
import com.developer.platform.infrastructure.enums.MenuEnum;
import com.developer.platform.infrastructure.enums.StatusEnum;
import com.developer.platform.infrastructure.repository.MenuRepository;
import com.developer.platform.infrastructure.error.MenuErrorType;
import com.veeker.core.exceptions.BusinessException;
import java.util.List;
import org.springframework.stereotype.Service;

/**
 * @author ：qiaoliang
 * @date ：2020-11-09
 */
@Service
public class MenuServiceImpl implements IMenuService {

    private final MenuRepository menuRepository;
    private final MenuEventPublisher menuEventPublisher;

    public MenuServiceImpl(MenuRepository menuRepository,
                           MenuEventPublisher menuEventPublisher) {
        this.menuRepository = menuRepository;
        this.menuEventPublisher = menuEventPublisher;
    }

    @Override
    public List<Menu> loadResourceDefine() {
        return menuRepository.findByStatusType(StatusEnum.Y, MenuEnum.F);
    }

    @Override
    public List<Menu> usersCanAccessResources(long id) {
        return menuRepository.findByUserId(id);
    }

    @Override
    public void save(Menu menu) {
        menuRepository.save(menu);
        menuEventPublisher.asyncPublish(new MenuEvent());
    }

    @Override
    public void delete(long id) {
        BusinessException.isTrue(menuRepository.parentCount(id) >0,
            MenuErrorType.DELETE_PARENT_IS_NOT_NULL_ERROR);
        menuRepository.delete(id);
        menuEventPublisher.asyncPublish(new MenuEvent());
    }

    @Override
    public void updateInfo(Menu menu) {
        menuRepository.updateById(menu);
        menuEventPublisher.asyncPublish(new MenuEvent());
    }

}
